{% extends "base.html" %}
{% load widget_tweaks %}

{% block title %}报警记录{% endblock %}

{% block content %}
<div class="dashboard-container">
    <div class="card mb-4">
        <div class="card-header">
            <h3 class="card-title h5 mb-0">
                <i class="bi bi-bell"></i> 报警记录查询
            </h3>
        </div>
        <div class="card-body">
            <form method="get" class="row g-3">
                {# 报警时间 #}
                <div class="col-md-6">
                    <label class="form-label">报警时间</label>
                    <div class="row g-2">
                        <div class="col">
                            {% render_field filter.form.created_at_after class="form-control" placeholder="开始时间" type="datetime-local" %}
                        </div>
                        <div class="col">
                            {% render_field filter.form.created_at_before class="form-control" placeholder="结束时间" type="datetime-local" %}
                        </div>
                    </div>
                </div>

                {# 订阅类型 #}
                <div class="col-md-2">
                    <label class="form-label">类型</label>
                    {% render_field filter.form.subscription_type class="form-select" %}
                </div>

                {# 数据源 #}
                <div class="col-md-2">
                    <label class="form-label">数据源</label>
                    {% render_field filter.form.data_source class="form-select" %}
                </div>

                {# 确认状态 #}
                <div class="col-md-2">
                    <label class="form-label">状态</label>
                    {% render_field filter.form.acknowledged class="form-select" %}
                </div>

                {# 数据名称 #}
                <div class="col-md-3">
                    <label class="form-label">名称</label>
                    {% render_field filter.form.name class="form-control" placeholder="请输入数据名称" %}
                </div>

                {# 标识符 #}
                <div class="col-md-3">
                    <label class="form-label">标识符</label>
                    {% render_field filter.form.identifier class="form-control" placeholder="请输入标识符" %}
                </div>

                {# 监控项 #}
                <div class="col-md-3">
                    <label class="form-label">监控项</label>
                    {% render_field filter.form.values_id class="form-control" placeholder="请输入监控项" %}
                </div>

                {# 操作按钮 #}
                <div class="col-md-3 d-flex align-items-end">
                    <div class="btn-group w-100">
                        <button type="submit" class="btn btn-secondary">
                            <i class="bi bi-search"></i> 查询
                        </button>
                        <a href="{% url 'alarm_list' %}" class="btn btn-outline-secondary">
                            <i class="bi bi-x-circle"></i> 清除条件
                        </a>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h3 class="card-title h5 mb-0">
                <i class="bi bi-list"></i> 报警记录列表
            </h3>
            <span class="badge bg-secondary">共 {{ page_obj.paginator.count }} 条记录</span>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover align-middle">
                    <thead>
                        <tr>
                            <th>时间</th>
                            <th>类型</th>
                            <th>数据源</th>
                            <th>名称</th>
                            <th>标识符</th>
                            <th>监控项</th>
                            <th>触发值</th>
                            <th>报警信息</th>
                            <th>状态</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for alarm in alarms %}
                        <tr>
                            <td>{{ alarm.created_at|date:"Y-m-d H:i:s" }}</td>
                            <td>
                                {% if alarm.subscription_type == 'opcua' %}
                                    <span class="badge bg-primary">{{ alarm.get_subscription_type_display }}</span>
                                {% else %}
                                    <span class="badge bg-info">{{ alarm.get_subscription_type_display }}</span>
                                {% endif %}
                            </td>
                            <td>{{ alarm.get_data_source_name }}</td>
                            <td>{{ alarm.name }}</td>
                            <td>
                                <span class="text-truncate d-inline-block" style="max-width: 200px;" title="{{ alarm.get_identifier }}">
                                    {{ alarm.get_identifier }}
                                </span>
                            </td>
                            <td>
                                {% if alarm.mqtt_item %}
                                    <span class="text-truncate d-inline-block" style="max-width: 150px;" title="{{ alarm.mqtt_item.values_id }}">
                                        {{ alarm.mqtt_item.values_id }}
                                    </span>
                                {% else %}
                                    -
                                {% endif %}
                            </td>
                            <td>{{ alarm.value|floatformat:2 }}</td>
                            <td>
                                <span class="text-truncate d-inline-block" style="max-width: 300px;" title="{{ alarm.message }}">
                                    {{ alarm.message }}
                                </span>
                            </td>
                            <td>
                                {% if alarm.acknowledged %}
                                    <span class="badge bg-success">
                                        <i class="bi bi-check-circle me-1"></i>已确认
                                        {% if alarm.acknowledged_by %}
                                        <br>
                                        <small>{{ alarm.acknowledged_by.username }}</small>
                                        {% endif %}
                                    </span>
                                {% else %}
                                    <div class="d-flex align-items-center">
                                        <span class="badge bg-danger me-2">
                                            <i class="bi bi-exclamation-circle me-1"></i>未确认
                                        </span>
                                        <button type="button" class="btn btn-sm btn-outline-primary acknowledge-btn" 
                                                data-alarm-id="{{ alarm.id }}"
                                                data-bs-toggle="modal" 
                                                data-bs-target="#acknowledgeModal">
                                            确认
                                        </button>
                                    </div>
                                {% endif %}
                            </td>
                        </tr>
                        {% empty %}
                        <tr>
                            <td colspan="8" class="text-center text-muted py-4">
                                <i class="bi bi-inbox fs-1 d-block mb-2"></i>
                                暂无报警记录
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>

            {% if is_paginated %}
            <nav aria-label="Page navigation" class="mt-4">
                <ul class="pagination justify-content-center">
                    {% if page_obj.has_previous %}
                    <li class="page-item">
                        <a class="page-link" href="?page=1">
                            <i class="bi bi-chevron-double-left"></i> 首页
                        </a>
                    </li>
                    <li class="page-item">
                        <a class="page-link" href="?page={{ page_obj.previous_page_number }}">
                            <i class="bi bi-chevron-left"></i> 上一页
                        </a>
                    </li>
                    {% else %}
                    <li class="page-item disabled">
                        <span class="page-link">
                            <i class="bi bi-chevron-double-left"></i> 首页
                        </span>
                    </li>
                    <li class="page-item disabled">
                        <span class="page-link">
                            <i class="bi bi-chevron-left"></i> 上一页
                        </span>
                    </li>
                    {% endif %}
            
                    <li class="page-item active">
                        <span class="page-link">
                            第 {{ page_obj.number }} 页 / 共 {{ page_obj.paginator.num_pages }} 页
                        </span>
                    </li>
            
                    {% if page_obj.has_next %}
                    <li class="page-item">
                        <a class="page-link" href="?page={{ page_obj.next_page_number }}">
                            下一页 <i class="bi bi-chevron-right"></i>
                        </a>
                    </li>
                    <li class="page-item">
                        <a class="page-link" href="?page={{ page_obj.paginator.num_pages }}">
                            末页 <i class="bi bi-chevron-double-right"></i>
                        </a>
                    </li>
                    {% else %}
                    <li class="page-item disabled">
                        <span class="page-link">
                            下一页 <i class="bi bi-chevron-right"></i>
                        </span>
                    </li>
                    <li class="page-item disabled">
                        <span class="page-link">
                            末页 <i class="bi bi-chevron-double-right"></i>
                        </span>
                    </li>
                    {% endif %}
                </ul>
            </nav>
            {% endif %}
        </div>
    </div>
</div>

<!-- 确认模态框 -->
<div class="modal fade" id="acknowledgeModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">确认报警</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="acknowledgeForm">
                    {% csrf_token %}
                    <input type="hidden" id="alarmId" name="alarm_id">
                    <div class="mb-3">
                        <label for="note" class="form-label">确认备注</label>
                        <textarea class="form-control" id="note" name="note" rows="3" 
                                placeholder="请输入确认备注（可选）"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="confirmAcknowledge">
                    <i class="bi bi-check-circle"></i> 确认
                </button>
            </div>
        </div>
    </div>
</div>

{% block extra_js %}
<script>
function resetForm() {
    // 清空所有表单字段
    const form = document.getElementById('search-form');
    const inputs = form.querySelectorAll('input, select');
    inputs.forEach(input => {
        if (input.type === 'checkbox') {
            input.checked = false;
        } else {
            input.value = '';
        }
    });
    
    // 提交表单
    form.submit();
}

// 分页链接处理
document.addEventListener('DOMContentLoaded', function () {
    // 获取当前URL的查询参数（除了page参数）
    const currentUrl = new URL(window.location.href);
    const searchParams = new URLSearchParams();
    
    // 保留除page之外的所有参数
    for (const [key, value] of currentUrl.searchParams.entries()) {
        if (key !== 'page') {
            searchParams.append(key, value);
        }
    }
    
    // 更新分页链接
    const paginationLinks = document.querySelectorAll('.pagination .page-link[href]');
    paginationLinks.forEach(link => {
        const pageMatch = link.href.match(/[?&]page=(\d+)/);
        if (pageMatch) {
            const pageNum = pageMatch[1];
            let newUrl = `?page=${pageNum}`;
            
            // 添加其他查询参数
            const otherParams = searchParams.toString();
            if (otherParams) {
                newUrl += `&${otherParams}`;
            }
            
            link.href = newUrl;
        }
    });

    // 处理确认按钮点击事件
    const modal = document.getElementById('acknowledgeModal');
    const acknowledgeModal = new bootstrap.Modal(modal);
    
    document.querySelectorAll('.acknowledge-btn').forEach(button => {
        button.addEventListener('click', function() {
            const alarmId = this.dataset.alarmId;
            document.getElementById('alarmId').value = alarmId;
        });
    });
    
    // 处理确认提交
    document.getElementById('confirmAcknowledge').addEventListener('click', function() {
        const form = document.getElementById('acknowledgeForm');
        const formData = new FormData(form);
        
        // 发送确认请求
        fetch('/alarms/acknowledge/', {
            method: 'POST',
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 关闭模态框
                acknowledgeModal.hide();
                // 刷新页面
                window.location.reload();
            } else {
                alert('确认失败：' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('确认失败，请重试');
        });
    });
});
</script>
{% endblock %}

{% endblock %} 